use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use anyhow::Result;
use time::OffsetDateTime;
use serde_json::Value;
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone)]
pub struct Database {
    users: Arc<RwLock<HashMap<i32, User>>>,
    roles: Arc<RwLock<HashMap<i32, Role>>>,
    menus: Arc<RwLock<HashMap<i32, Menu>>>,
    route_rules: Arc<RwLock<HashMap<i32, RouteRule>>>,
    gateway_configs: Arc<RwLock<HashMap<i32, GatewayConfig>>>,
    next_id: Arc<RwLock<i32>>,
}

impl Database {
    pub fn new(config: &crate::config::DatabaseConfig) -> Self {
        println!("使用配置初始化数据库: {:?}", config);
        Self {
            users: Arc::new(RwLock::new(HashMap::new())),
            roles: Arc::new(RwLock::new(HashMap::new())),
            menus: Arc::new(RwLock::new(HashMap::new())),
            route_rules: Arc::new(RwLock::new(HashMap::new())),
            gateway_configs: Arc::new(RwLock::new(HashMap::new())),
            next_id: Arc::new(RwLock::new(1)),
        }
    }

    fn get_next_id(&self) -> i32 {
        let mut next_id = self.next_id.write().unwrap();
        let id = *next_id;
        *next_id += 1;
        id
    }

    pub fn add_user(&self, user: User) -> i32 {
        let id = self.get_next_id();
        let mut user = user;
        user.id = id;
        self.users.write().unwrap().insert(id, user);
        id
    }

    pub fn get_user(&self, id: i32) -> Option<User> {
        self.users.read().unwrap().get(&id).cloned()
    }

    pub fn get_user_by_username(&self, username: &str) -> Option<User> {
        self.users.read().unwrap().values()
            .find(|user| user.username == username)
            .cloned()
    }

    pub fn update_user(&self, id: i32, user: User) -> bool {
        let mut users = self.users.write().unwrap();
        if users.contains_key(&id) {
            users.insert(id, user);
            true
        } else {
            false
        }
    }

    pub fn delete_user(&self, id: i32) -> bool {
        self.users.write().unwrap().remove(&id).is_some()
    }

    pub fn get_all_users(&self) -> Vec<User> {
        self.users.read().unwrap().values().cloned().collect()
    }

    // 角色管理方法
    pub fn add_role(&self, role: Role) -> i32 {
        let id = self.get_next_id();
        let mut role = role;
        role.id = id;
        self.roles.write().unwrap().insert(id, role);
        id
    }

    pub fn get_role(&self, id: i32) -> Option<Role> {
        self.roles.read().unwrap().get(&id).cloned()
    }

    pub fn update_role(&self, id: i32, role: Role) -> bool {
        let mut roles = self.roles.write().unwrap();
        if roles.contains_key(&id) {
            roles.insert(id, role);
            true
        } else {
            false
        }
    }

    pub fn delete_role(&self, id: i32) -> bool {
        self.roles.write().unwrap().remove(&id).is_some()
    }

    pub fn get_all_roles(&self) -> Vec<Role> {
        self.roles.read().unwrap().values().cloned().collect()
    }

    // 菜单管理方法
    pub fn add_menu(&self, menu: Menu) -> i32 {
        let id = self.get_next_id();
        let mut menu = menu;
        menu.id = id;
        self.menus.write().unwrap().insert(id, menu);
        id
    }

    pub fn get_menu(&self, id: i32) -> Option<Menu> {
        self.menus.read().unwrap().get(&id).cloned()
    }

    pub fn update_menu(&self, id: i32, menu: Menu) -> bool {
        let mut menus = self.menus.write().unwrap();
        if menus.contains_key(&id) {
            menus.insert(id, menu);
            true
        } else {
            false
        }
    }

    pub fn delete_menu(&self, id: i32) -> bool {
        self.menus.write().unwrap().remove(&id).is_some()
    }

    pub fn get_all_menus(&self) -> Vec<Menu> {
        self.menus.read().unwrap().values().cloned().collect()
    }

    pub fn get_menu_tree(&self) -> Vec<Menu> {
        // 简化实现：返回所有菜单，前端可以处理树形结构
        self.menus.read().unwrap().values().cloned().collect()
    }

    // 路由规则管理方法
    pub fn add_route_rule(&self, route_rule: RouteRule) -> i32 {
        let id = self.get_next_id();
        let mut route_rule = route_rule;
        route_rule.id = id;
        self.route_rules.write().unwrap().insert(id, route_rule);
        id
    }

    pub fn get_route_rule(&self, id: i32) -> Option<RouteRule> {
        self.route_rules.read().unwrap().get(&id).cloned()
    }

    pub fn update_route_rule(&self, id: i32, route_rule: RouteRule) -> bool {
        let mut route_rules = self.route_rules.write().unwrap();
        if route_rules.contains_key(&id) {
            route_rules.insert(id, route_rule);
            true
        } else {
            false
        }
    }

    pub fn delete_route_rule(&self, id: i32) -> bool {
        self.route_rules.write().unwrap().remove(&id).is_some()
    }

    pub fn get_all_route_rules(&self) -> Vec<RouteRule> {
        self.route_rules.read().unwrap().values().cloned().collect()
    }

    // 网关配置管理方法
    pub fn add_gateway_config(&self, gateway_config: GatewayConfig) -> i32 {
        let id = self.get_next_id();
        let mut gateway_config = gateway_config;
        gateway_config.id = id;
        self.gateway_configs.write().unwrap().insert(id, gateway_config);
        id
    }

    pub fn get_gateway_config(&self, id: i32) -> Option<GatewayConfig> {
        self.gateway_configs.read().unwrap().get(&id).cloned()
    }

    pub fn get_gateway_config_by_key(&self, key: &str) -> Option<GatewayConfig> {
        self.gateway_configs.read().unwrap().values()
            .find(|config| config.config_key == key)
            .cloned()
    }

    pub fn update_gateway_config(&self, id: i32, gateway_config: GatewayConfig) -> bool {
        let mut gateway_configs = self.gateway_configs.write().unwrap();
        if gateway_configs.contains_key(&id) {
            gateway_configs.insert(id, gateway_config);
            true
        } else {
            false
        }
    }

    pub fn delete_gateway_config(&self, id: i32) -> bool {
        self.gateway_configs.write().unwrap().remove(&id).is_some()
    }

    pub fn get_all_gateway_configs(&self) -> Vec<GatewayConfig> {
        self.gateway_configs.read().unwrap().values().cloned().collect()
    }
}

// 数据库模型定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: i32,
    pub username: String,
    pub email: String,
    pub password_hash: String,
    pub full_name: Option<String>,
    pub phone: Option<String>,
    pub status: String,
    pub last_login: Option<OffsetDateTime>,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
    pub created_by: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    pub id: i32,
    pub role_name: String,
    pub description: Option<String>,
    pub permissions: Value,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Menu {
    pub id: i32,
    pub parent_id: Option<i32>,
    pub menu_name: String,
    pub menu_path: Option<String>,
    pub menu_icon: Option<String>,
    pub menu_type: String,
    pub sort_order: i32,
    pub is_visible: bool,
    pub permissions: Value,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteRule {
    pub id: i32,
    pub rule_name: String,
    pub match_pattern: String,
    pub target_url: String,
    pub method: String,
    pub priority: i32,
    pub is_active: bool,
    pub timeout_ms: i32,
    pub retry_count: i32,
    pub rate_limit: i32,
    pub headers_config: Value,
    pub rewrite_config: Value,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
    pub created_by: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayConfig {
    pub id: i32,
    pub config_key: String,
    pub config_value: Value,
    pub description: Option<String>,
    pub config_type: String,
    pub is_active: bool,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
    pub created_by: Option<i32>,
}